var preferences = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService).getBranch("extensions.crunchtime.");
var parseService = Components.classes["@crunch.time/ctparseservice;1"].createInstance(Components.interfaces.CTParseServiceInt);


// Called when user clicks on menu option "CrunchTime" to decide which window to show
function openWindow()
{
    // User has not set which folder to store CTPreferences, prompts user to pick
	if(preferences.getCharPref("basepath") !="")
    {
		window.openDialog("chrome://crunchtime/content/pref_window.xul", "crunchTimePreferences", "chrome,all,resizable=no");
    }
    // User has initially chosen which folder to store CTPreferences
    else
    {
		window.openDialog("chrome://crunchtime/content/init_pref_window.xul", "crunchTimeInit", "chrome,all,resizable=no");
    }
}

// Called when user clicks on status toolbar icon in lower right hand corner of frame
function openAlertWindow()
{
    window.openDialog("chrome://crunchtime/content/alert_window.xul", "", "chrome");
}

// Initially reads the EventList and SiteList files to populate xul list components
function onLoad()
{
    readFile("eventpath", "taskList");
    readFile("sitepath","blockedSiteList");
	readFile("scheduledpath","scheduleBlockingList");
	
    document.getElementById('redirectsite').value = preferences.getCharPref("redirectsite");
    document.getElementById('blockbefore').value = preferences.getIntPref("blockbefore");
    document.getElementById('blockafter').value = preferences.getIntPref("blockafter");
    document.getElementById('basepathWindow').value = preferences.getCharPref("basepath");
	
    // Checks to see if redirect site and basepath are set, if so remove the check stars and disable save button
    if(document.getElementById('redirectsite').value != "" && document.getElementById('basepathWindow').value != "")
    {
		document.getElementById('redirectSiteCheck').setAttribute('hidden', 'true');
		document.getElementById('basepathCheck').setAttribute('hidden', 'true');
		document.getElementById('settingSaveButton').setAttribute('disabled', 'false');
    }
    else
    {
		if(document.getElementById('redirectsite').value != "")
			document.getElementById('redirectSiteCheck').setAttribute('hidden', 'true');
		if(document.getElementById('basepathWindow').value != "")
			document.getElementById('basepathCheck').setAttribute('hidden', 'true');
		document.getElementById('settingSaveButton').setAttribute('disabled', 'true');
    }
}

// Called after user has clicked save in the window prompt for the folder to store CT Preferences
function openPreferences(basepath)
{
    // call setPrefPaths() using the given basepath
    setPrefPaths(basepath);
    preferences.setCharPref("basepath", basepath);
    // Close CT Preference prompt and open main preferences window
    window.close();
    window.openDialog("chrome://crunchtime/content/pref_window.xul", "crunchTimePreferences", "chrome,all,resizable=no");
}

// Sets up the CT Preferences files stored on disk
function setPrefPaths(inputBasePath)
{
    // If user has changed the basePath, update it, else use basepath stored in extension prefs
    var basePath;
    if(inputBasePath == ""){
		//MAKE SURE WE'RE RESTORING SETTINGS HERE
		basePath = preferences.getCharPref("basepath");
    }
    else{
		basePath = inputBasePath;
    }
	
	if(basePath == "eventpath") { //if we don't have a basepath, create one
		window.openDialog("chrome://crunchtime/content/init_pref_window.xul", "crunchTimeInit", "chrome,all,resizable=no");
		basePath = preferences.getCharPref("basepath");
	}
    var sitePath = basePath+"/sitelist.txt";
    var eventPath = basePath+"/eventlist.txt";
	var scheduledPath = basePath+"/scheduledlist.txt";
    var baseDir = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
    baseDir.initWithPath(basePath);
    if( !baseDir.exists() || !baseDir.isDirectory() ) {   // if it doesn't exist, create
		baseDir.create(Components.interfaces.nsIFile.DIRECTORY_TYPE, 0777);
    }
	
    // Create SiteList file if it does not exist
    var siteListfile = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
    siteListfile.initWithPath(sitePath);
    if( !siteListfile.exists() )  // if it doesn't exist, create
		siteListfile.create(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 0777);
    // Store sitepath in extension prefs
    preferences.setComplexValue("sitepath", Components.interfaces.nsILocalFile, siteListfile);
	
	// Create SiteList file if it does not exist
    var scheduledListfile = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
    scheduledListfile.initWithPath(scheduledPath);
    if( !scheduledListfile.exists() )  // if it doesn't exist, create
		scheduledListfile.create(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 0777);
    // Store sitepath in extension prefs
    preferences.setComplexValue("scheduledpath", Components.interfaces.nsILocalFile, scheduledListfile);
	
	
    // Create EventList file if it does not exist
    var eventListfile = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
    eventListfile.initWithPath(eventPath);
    if( !eventListfile.exists() )  // if it doesn't exist, create
		eventListfile.create(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 0777);
    // Store eventpath in extension prefs
    preferences.setComplexValue("eventpath", Components.interfaces.nsILocalFile, eventListfile);
}

// Checks if textbox input is valid (not containing *) and if it is not empty
function checkInput(item, check, button)
{
    var el = document.getElementById(item).value;
	
    // Input is empty, display red check and disable appropriate button
    if(el == "")
    {
		document.getElementById(check).setAttribute('hidden', 'false');
		document.getElementById(button).setAttribute('disabled', 'true');
		
    }
    // Input contains *, display red check, disable appropriate button, and alert user
    else if(el.indexOf("*") != -1)
    {
		document.getElementById(check).setAttribute('hidden', 'false');
		document.getElementById(button).setAttribute('disabled', 'true');
		alert("Field cannot contain *");
    }
    // Input is valid, hide red check and enable appropriate button
    else
    {
		document.getElementById(check).setAttribute('hidden', 'true');
		document.getElementById(button).setAttribute('disabled', 'false');
    }
	
    // Confirm that both redirect site and base path inputs are valid in order to enable save button
    if(button == "settingSaveButton")
    {
		if(document.getElementById('redirectsite').value != "" && document.getElementById('basepath').value != "")
			document.getElementById('settingSaveButton').setAttribute('disabled', 'false');
		else
			document.getElementById('settingSaveButton').setAttribute('disabled', 'true');
    }
}

// Add a new task with the user input
function addTask()
{
    var taskName = document.getElementById('taskNameInput').value;
    var datePicker = document.getElementById('taskDatePicker');
    var timePicker =document.getElementById('taskTimePicker');
	
	var monthname=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
	var hour = timePicker.hour;
	if (hour <10)
		hour = "0"+timePicker.hour;
	var minute = timePicker.minute;
	if (minute <10)
		minute = "0"+timePicker.minute;
	var day = datePicker.date;
	if (day <10)
		day = "0"+datePicker.date;
	var date = monthname[datePicker.month] +" "+ day+", " + datePicker.year +" "+hour+":"+minute+":00";
	
    // Call CTParseService to add task to its list
    parseService.addTask(taskName, date);
    // Update list based on files stored on disk
    readFile("eventpath", "taskList");
    document.getElementById('taskNameInput').value = "";
	document.getElementById('taskCompleteButton').setAttribute('disabled','true');
	document.getElementById('taskEditButton').setAttribute('disabled','true');
	document.getElementById('taskDeleteButton').setAttribute('disabled','true');
}


// Select task to edit, change Add Task to Edit Task
function selectEditTask()
{
	document.getElementById('addeditLabel').setAttribute('value', 'Edit Task');
	document.getElementById('taskAddButton').setAttribute('hidden', 'true');
	document.getElementById('taskEditSave').setAttribute('hidden', 'false');
	document.getElementById('taskEditCancel').setAttribute('hidden', 'false');
	
	var task = document.getElementById('taskList').value.split("*");
	document.getElementById('originaltask').value= task[0];
	document.getElementById('taskNameInput').value= task[0];
	var d = new Date(task[1]);
	var datestring = d.getFullYear()+"-"+(d.getMonth()+1)+"-"+d.getDate();
	var timestring = d.getHours()+":"+d.getMinutes();
	
	document.getElementById('taskDatePicker').value = datestring;
	document.getElementById('taskTimePicker').value = timestring;
}
function cancelEditTask()
{
	document.getElementById('taskNameInput').value = "";
	document.getElementById('addeditLabel').setAttribute('value', 'Add Task');
	document.getElementById('taskAddButton').setAttribute('hidden', 'false');
	document.getElementById('taskEditSave').setAttribute('hidden', 'true');
	document.getElementById('taskEditCancel').setAttribute('hidden', 'true');
	
}

// Update task with edited information
function editTask()
{
	var originalTaskName = document.getElementById('originaltask').value;
	// Call CTParseService to remove task from list
    parseService.removeTask(originalTaskName);
	readFile("eventpath", "taskList");
	
	var taskName = document.getElementById('taskNameInput').value;
    var datePicker = document.getElementById('taskDatePicker');
    var timePicker =document.getElementById('taskTimePicker');
	var monthname=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
	var hour = timePicker.hour;
	if (hour <10)
		hour = "0"+timePicker.hour;
	var minute = timePicker.minute;
	if (minute <10)
		minute = "0"+timePicker.minute;
	var day = datePicker.date;
	if (day <10)
		day = "0"+datePicker.date;
	var date = monthname[datePicker.month] +" "+ day+", " + datePicker.year +" "+hour+":"+minute+":00";
	
    // Call CTParseService to add task to its list
    parseService.addTask(taskName, date);
    // Update list based on files stored on disk
    readFile("eventpath", "taskList");
	
    document.getElementById('taskNameInput').value = "";
	document.getElementById('addeditLabel').setAttribute('value', 'Add Task');
	document.getElementById('taskAddButton').setAttribute('hidden', 'false');
	document.getElementById('taskEditSave').setAttribute('hidden', 'true');
	document.getElementById('taskEditCancel').setAttribute('hidden', 'true');
	document.getElementById('taskCompleteButton').setAttribute('disabled','true');
	document.getElementById('taskEditButton').setAttribute('disabled','true');
	document.getElementById('taskDeleteButton').setAttribute('disabled','true');
}

// Remove task selected by user
function removeTask()
{
    var task = document.getElementById('taskList').value.split("*");
	
	// Call CTParseService to remove task from list
    parseService.removeTask(task[0]);
	
    // Update lists based on files stored on disk
    readFile("eventpath", "taskList");
	document.getElementById('taskCompleteButton').setAttribute('disabled','true');
	document.getElementById('taskEditButton').setAttribute('disabled','true');
	document.getElementById('taskDeleteButton').setAttribute('disabled','true');
}

// Add time block with user input
function addBlockTime()
{
    var datePicker = document.getElementById('scheduledDatePicker');
    var timePicker =document.getElementById('scheduledTimePicker');
	
	var monthname=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
	var hour = timePicker.hour;
	if (hour <10)
		hour = "0"+timePicker.hour;
	var minute = timePicker.minute;
	if (minute <10)
		minute = "0"+timePicker.minute;
	var day = datePicker.date;
	if (day <10)
		day = "0"+datePicker.date;
	var date = monthname[datePicker.month] +" "+ day+", " + datePicker.year +" "+hour+":"+minute+":00";
	var currentDate = new Date();
	var taskName = currentDate.getTime();
	
    // Call CTParseService to blocked time to its list
    parseService.addScheduled(taskName, date);
	// Update list based on files stored on disk
    readFile("scheduledpath", "scheduleBlockingList");
	
	// Add it to tasks since it should appear right away
	parseService.addTask("Daily Scheduled Blocking", date);
	// Update list based on files stored on disk
    readFile("eventpath", "taskList");
}

// Remove blocked time selected by user
function deleteBlockTime()
{
	var blockTime = document.getElementById('scheduleBlockingList').value;
    // Call CTParseService to remove block time from list
    parseService.removeScheduled(blockTime);
    // Update lists based on files stored on disk 
	readFile("scheduledpath", "scheduleBlockingList");
	
	
	var chunks = blockTime.split("*");
//alert("passed"+chunks[1]);
	// Call CTParseService to remove block time from list
    parseService.(chunks[1]);
    // Update lists based on files stored on disk
    readFile("eventpath", "taskList");

}

// Add site with user input
function addSite()
{
    var siteName = document.getElementById('blockedSite').value;
	if (siteName != "")
	{
		// Call CTParseService to add site to list
		parseService.addSite(siteName);
		// Update lists based on files stored on disk
		readFile("sitepath","blockedSiteList");
		document.getElementById('blockedSite').value = "";
	}
}

// Remove site selected by user
function removeSite()
{
	var siteName = document.getElementById('blockedSiteList').value;
    // Call CTParseService to remove site from list
    parseService.removeSite(siteName);
    // Update lists based on files stored on disk
    readFile("sitepath", "blockedSiteList");
}

// Shortcut function for enabling buttons
function enableButtons(button1, button2, button3)
{
    if(button1 !="")
		document.getElementById(button1).setAttribute('disabled', 'false');
    if(button2 !="")
		document.getElementById(button2).setAttribute('disabled', 'false');
    if(button3 !="")
		document.getElementById(button3).setAttribute('disabled', 'false');
}

// Read files off disk and update appropriate list
function readFile(prefFile, listName)
{
    var file = preferences.getComplexValue(prefFile, Components.interfaces.nsILocalFile);
    var istream = Components.classes["@mozilla.org/network/file-input-stream;1"].createInstance(Components.interfaces.nsIFileInputStream);
    try{
		// Open file for reading
		istream.init(file, 0x01, 0444, 0);
		istream.QueryInterface(Components.interfaces.nsILineInputStream);
    }
    catch(e) {
		//The file doesn't exist
		//recreate it
		setPrefPaths(prefFile);
    }
	
    // read lines into array
    var line = {}, lines = [], hasmore;
    do {
		hasmore = istream.readLine(line);
		lines.push(line.value);
    } while(hasmore);
    istream.close();
	
    // Clear list component of entries so it can be updated
    var list = document.getElementById(listName);
    while(list.getRowCount() != 0)
		list.removeItemAt(0);
	
    // Parse text from files and add to appropriate list
    for(var i=0; i<lines.length; i++)
    {
		if(prefFile == "eventpath")
		{
			var chunks = lines[i].split("*");
			if(chunks.length ==2)
			{
			//	if(chunks[0]!="Daily Scheduled Blocking")
			//	{
				var row = document.createElement('listitem');
				row.setAttribute('value', lines[i]); 
				var cell = document.createElement('listcell');
				cell.setAttribute('label', chunks[0]);
				row.appendChild(cell);
				
				cell = document.createElement('listcell');
				cell.setAttribute('label', chunks[1] );
				row.appendChild(cell);
				
				list.appendChild(row);
			//	}
			}
		}
		else if(prefFile == "scheduledpath")
		{
			var chunks3 = lines[i].split("*");
			if(chunks3.length ==2)
			{
				var row3 = document.createElement('listitem');
				row3.setAttribute('value', lines[i]); 
				var cell3 = document.createElement('listcell');
				cell3.setAttribute('label', chunks3[1]);
				row3.appendChild(cell3);
				list.appendChild(row3);
			}
		}
		else if(prefFile == "sitepath")
		{
			var row2 = document.createElement('listitem');
			row2.setAttribute('value', lines[i]); 
			var cell2 = document.createElement('listcell');
			cell2.setAttribute('label', lines[i]);
			row2.appendChild(cell2);
			list.appendChild(row2);
		}
    }
}

// Save settings to preferences
function saveSettings()
{
    preferences.setCharPref("redirectsite", document.getElementById('redirectsite').value);
    preferences.setIntPref("blockbefore", document.getElementById('blockbefore').value);
    preferences.setIntPref("blockafter", document.getElementById('blockafter').value);
    preferences.setCharPref("basepath", document.getElementById('basepathWindow').value);
	
    // Incase basepath has been changed, make sure to recreate folder and files for CT Preferences
    setPrefPaths(document.getElementById('basepathWindow').value);
	readFile("eventpath", "taskList");
	readFile("sitepath","blockedSiteList");
}

// Called when unblock button in CrunchTime Status window is clicked
// This unblocks the user and removes event from list if it does not repeat
function unblock()
{
	if(parseService.wouldBlock())
	{
		// Call CTParseService to remove task from list
		parseService.removeAllBlockingTasks();
		document.getElementById("statusMsg").childNodes[0].nodeValue = "CrunchTime is not blocking right now.";
		document.getElementById("unblockButton").setAttribute('disabled', 'true');
	}
}


// Creates xul filepicker to select which folder to store CT Preferences
function folderPicker()
{
    var filepicker = Components.classes["@mozilla.org/filepicker;1"].createInstance(Components.interfaces.nsIFilePicker);
    filepicker.init(window, "Select a Folder", filepicker.modeGetFolder);
    filepicker.show();
	
    // Update textbox to reflect users choice
    if (filepicker.file)
		document.getElementById('basepath').value = filepicker.file.path;
}

// Update text in CrunchTime status window
function getStatusMsg()
{
	if(parseService.wouldBlock())
	{
		var task = parseService.blockingTask();
		document.getElementById("statusMsg").childNodes[0].nodeValue = "CrunchTime is blocking due to: "+task;
		document.getElementById("unblockButton").setAttribute('disabled', 'false');
	}
	else
	{
		document.getElementById("statusMsg").childNodes[0].nodeValue = "CrunchTime is not blocking right now.";
		document.getElementById("unblockButton").setAttribute('disabled', 'true');
	}
}
